#include "qmydb.h"

//add by dimon, 2024-03-17 17:28
#include <QSqlDriver>
#include <QtDebug>
#include <QThread>
#include <QSqlError>

QMyDB::QMyDB(QObject *parent) : QObject(parent)
{

}

//add by dimon, 2024-03-17 17:28

//数据库操作
//连接数据库
void QMyDB::connectDB()
{

    db = QSqlDatabase::addDatabase("QMYSQL"); //指定数据库引擎为 MySQL 数据库
    db.setHostName("localhost");
    db.setDatabaseName("db_chat");
    db.setUserName("root");
    db.setPassword("123456");

    if(!db.open()){
        QMessageBox::critical(NULL, tr("连接数据库"), tr("连接数据库失败。"));
    }
    else{
       // QMessageBox::information(NULL,tr("连接数据库"), tr("连接数据库成功。"));
    }
}

 //关闭数数据库
void QMyDB::closeDB()
{
    db.close();
}

//数据访问接口

//获取用户信息
bool QMyDB::getUserInfo(quint32 id, QUser *pUser)
{
    bool result = false;

    //连接数据库
    this->connectDB();

    qDebug() << __FILE__<< __FUNCTION__ << "(): " << "getUserInfo";

    //数据库Query操作
    QSqlQuery query;
    if(!(query.exec("SELECT * FROM tb_user WHERE id=" + QString::number(id)))){
            qDebug() << __FILE__<< __FUNCTION__ << "(): " << query.lastError().driverText();
            qDebug() << __FILE__<< __FUNCTION__ << "(): " << query.lastError().databaseText();
            return false;
    }

    //从数据库Query请求节结果中获取原始数据
    if(query.next()){ //'next'获取查询结果下一条
        qDebug() << __FILE__<< __FUNCTION__ << "(): " << "getUserInfo success";

        pUser->id = query.value("id").toUInt();
        pUser->password = query.value("password").toString();
        pUser->name = query.value("name").toString();
        pUser->sex = query.value("sex").toBool();
        pUser->birthday = query.value("birthday").toDate();
        pUser->description = query.value("description").toString();

        qDebug() << __FILE__<< __FUNCTION__ << "(): " << pUser->id;
        qDebug() << __FILE__<< __FUNCTION__ << "(): " << pUser->name;
        qDebug() << __FILE__<< __FUNCTION__ << "(): " << pUser->password;

        result = true;
    }

    //关闭数据库
    this->closeDB();

    return result;
}

//新建用户
quint32 QMyDB::newUser(QString password, QString name, bool sex,
                QDate birthday,
                QString description)
{
    //连接数据库
    this->connectDB();
    QSqlQuery query;

    qDebug() << "QTcpThread run(), current thread is: " << QThread::currentThread();
    qDebug() << "连接数据库";

    //插入新用户到数据库DB
    query.prepare("INSERT INTO tb_user (password, name, sex, birthday, description) "
                  "VALUES(:password, :name, :sex, :birthday, :description)");
    query.bindValue(":password", password);
    query.bindValue(":name", name);
    query.bindValue(":sex", sex);
    query.bindValue(":birthday", birthday);
    query.bindValue(":description", description);

    qDebug() << " exec query " << query.lastQuery();

    if(!query.exec()){
        qDebug() << "Database query fail";
        qDebug() << query.lastError().driverText();
        qDebug() << query.lastError().databaseText();
    }

    qDebug() << " exec query " << query.lastQuery();

    //返回新用户的userID
    quint32 userid = 0;
    //查询数据库DB 最后一次执行返回的auto_incremetn的id值
    query.exec("SELECT LAST_INSERT_ID()");

    qDebug() << query.lastError().driverText();
    qDebug() << query.lastError().databaseText();

    if(query.next()){
        userid = query.value(0).toUInt();
    }
    qDebug() << "userid = " << userid;

    qDebug() << "QTcpThread run(), current thread is: " << QThread::currentThread();
    qDebug() << "关闭数据库";
    //关闭数据库
    this->closeDB();

    return userid;
}

//获取用户列表
int QMyDB::getUserList(QList<quint32> *listID, QStringList *listName)
{
    int count = 0;

    //连接数据库
    this->connectDB();
    QSqlQuery query;
    listID->clear();
    listName->clear();

    //查询
    //准备数据库DB查询对象QSqlQuery
    if(!(query.prepare("SELECT id, name FROM tb_user")))
        count = -1;

    //执行数据库查询QSqlQuery
    if(!(query.exec()))
        count = -1;

    //数据加入列表
    while(query.next()){
        listID->append(query.value(0).toUInt());
        listName->append(query.value(1).toString());
    }

    //获取记录数
    if(db.driver()->hasFeature(QSqlDriver::QuerySize))
        count = query.size();
    else{
        query.last();
        count = query.at()+1;
    }

    //关闭数据库
    this->connectDB();

    return count;
}
